//
//  TXRefreshHeader.m
//  TXKit
//
//  Created by YM on 17/3/18.
//  Copyright © 2017年 Tincent. All rights reserved.
//

#import "TXRefreshHeader.h"
#import "TXKitMacro.h"

#define kHeaderImage                [UIImage imageNamed:@"refresh_img_up"]

#define kRefHeaderIdleText          @"下拉刷新"
#define kRefHeaderPullingText       @"释放更新"
#define kRefHeaderRefreshingText    @"正在刷新"


@interface TXRefreshHeader ()
{
    CABasicAnimation *rotationAnimation;
}

@property (nonatomic, strong) UIImageView *rotateImgView;

@end

@implementation TXRefreshHeader

#pragma mark - Help Method

//图片360°选装动画
-(void)rotate360DegreeWithImageView {

    if (!rotationAnimation) {
        rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; //让其在z轴旋转
        rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];//旋转角度
        rotationAnimation.duration = 1; //旋转周期
        rotationAnimation.cumulative = YES;//旋转累加角度
        rotationAnimation.repeatCount = 100000;//旋转次数
        [self.rotateImgView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    }
}

#pragma mark - OverWrite

- (void)prepare {
    
    [super prepare];
    
    _rotateImgView = [[UIImageView alloc] initWithImage:kHeaderImage];

    //添加需要旋转的图片，如果可以提供gif图的话，可以省略这一步，直接将gif图设置为logoView
    [self.gifView addSubview:_rotateImgView];
    
    
    //根据拖拽的情况自动切换透明度(在导航栏下面自动隐藏)
    self.automaticallyChangeAlpha = YES;
    
    //隐藏时间
    self.lastUpdatedTimeLabel.hidden = YES;
    
    //文字距离圈圈的距离
    self.labelLeftInset = 6;

    //根据需求设置字体颜色
    self.stateLabel.font = TX_FONT(14);
    self.stateLabel.textColor = TX_COLOR_FROM_RGB(0x999999);
    
    //根据需求设置刷新文字，不同状态的刷新文字都可以自定义
    [self setTitle:kRefHeaderIdleText forState:MJRefreshStateIdle];
    [self setTitle:kRefHeaderPullingText forState:MJRefreshStatePulling];
    [self setTitle:kRefHeaderRefreshingText forState:MJRefreshStateRefreshing];
}

//如果需要自己重新布局子控件
- (void)placeSubviews {
    
    [super placeSubviews];
    
    if (!(self.stateLabel.hidden && self.lastUpdatedTimeLabel.hidden)) {
        
        _rotateImgView.mj_x = self.gifView.mj_w - kHeaderImage.size.width;
        _rotateImgView.mj_y = (self.gifView.mj_h - kHeaderImage.size.height)/2;
    }
}

//如果是gif图的话，不需要重写这个方法
- (void)setPullingPercent:(CGFloat)pullingPercent {
    
    [super setPullingPercent:pullingPercent];
        
    if (self.state == MJRefreshStateWillRefresh ||
        (self.state == MJRefreshStatePulling && pullingPercent == 1.0)) {
        
        [self rotate360DegreeWithImageView];
    }

    if (self.state == MJRefreshStateIdle && pullingPercent == 0.0) {
        
        [self.rotateImgView.layer removeAllAnimations];
        
        rotationAnimation = nil;
    }
}

@end
